// utils/routerUtils.ts
import type { RouteRecordRaw } from 'vue-router'

const viewModules = require.context('../views', true, /\.vue$/)

const componentsMap: Record<string, () => void> = {}

viewModules.keys().forEach((key: string) => {
  const path = key.replace(/^\./, '') // 去掉 ./ 前缀
  componentsMap[path] = () => Promise.resolve(viewModules(key)) 
})

export function loadComponent(componentPath: string) {
  const fullPath = `${componentPath}.vue`
  return componentsMap[fullPath];
}

export function transformMenuToRoutes(menus: any[]): RouteRecordRaw[] {
  if (!menus || !Array.isArray(menus)) return []
  const routers = getFlatMenusByType(menus, 2);
  return routers.map(menu => ({
    path: menu.path,
    name: menu.name,
    component: loadComponent(menu.component),
    meta: {
      title: menu.name,
      isDelete: false
    }
  }))
}

/**
 * 扁平化菜单树，提取所有节点为 list
 */
export function flattenMenuToList(menuTree: any[]): any[] {
  return menuTree.reduce((acc, node) => {
    acc.push(node);

    if (node.children && node.children.length > 0) {
      acc.push(...flattenMenuToList(node.children));
    }

    return acc;
  }, [] as any[]);
}

/**
 * 组合函数：提取 menuType === 2 的菜单并扁平化返回
 */
export function getFlatMenusByType(menus: any[], type: number): any[] {
  const flattenList =  flattenMenuToList(menus);
  return flattenList.filter(item => item.menuType === type);
}